package com.cjh.controller;

import com.cjh.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("common")
public class CommonController {
    @Value("${reggie.images.path}")
    String basePath;

    @PostMapping("upload")
    public R<String> upload(@RequestPart("file") MultipartFile file) {
        //此时file是一个临时文件,需要转存才能保证不自动消失
        String originalFilename = file.getOriginalFilename();//file.jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));  //.jpg
        String fileName = UUID.randomUUID().toString()+suffix;

        //创建一个目录对象
        File dir=new File(basePath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        //输入流,通过输入流读取文件内容
        try {

            log.info(name);
            FileInputStream fileInputStream=new FileInputStream(basePath+name);
            //输出流,通过response获取输出流,将图片数据响应到页面上去
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");

            int length=0;
            byte[] bytes=new byte[1024];
            while((length=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,length);
                outputStream.flush();
            }

            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
